/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence;

import database.DBConnection;
import java.util.ArrayList;
import java.util.HashMap;
import model.Guest;

/**
 *
 * @author Martin Mohr Pedersen
 */
public class GuestDAO {

    public Guest findByCpr(String cpr) {
        String sql = "SELECT * FROM guest WHERE cpr = ? LIMIT 1";
        Object[] args = new Object[] {cpr};
        
        return findOne(sql, args);
    }

    public void create(Guest guest) {
        
        String sql = "INSERT INTO guest(cpr, name, gender, birthdate) VALUES(?, ?, ?, ?)";
        
        Object[] args = new Object[] {guest.getCpr(), guest.getName(), 
            guest.getGender(), guest.getBirthdate()};
        
        DBConnection.getInstance().executeInsert(sql, args);
        
    }

    private Guest[] find(String sql, Object[] args) {
        ArrayList<HashMap<String, Object>> results = DBConnection.getInstance().executeSelect(sql, args);
        
        return unpack(results);
    }
    
    private Guest findOne(String sql, Object[] args) {
        Guest[] results = find(sql, args);
        
        if(results.length > 0) {
            return results[0];
        }
        
        return null;
    }

    private Guest[] unpack(ArrayList<HashMap<String, Object>> results) {
        ArrayList<Guest> guest = new ArrayList<Guest>();
        Guest oneGuest;
        for (HashMap<String, Object> row : results) {
            oneGuest = new Guest();
            
            java.sql.Timestamp birthdate = (java.sql.Timestamp) row.get("birthdate");
            oneGuest.setBirthdate(new java.util.Date(birthdate.getTime()));
            
            oneGuest.setCpr((String) row.get("cpr"));
            oneGuest.setName((String) row.get("name"));
            oneGuest.setGender((String)row.get("gender"));
            guest.add(oneGuest);
        }
        return guest.toArray(new Guest[guest.size()]);
        
    }
}
